package io.gitee.vexlife.snake;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 * @author vexu
 *
 */
public class GameLauncher {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			IAgent[] agents = null;
			File agentDir = new File("./agent_engines");
			if (agentDir.exists() && agentDir.isDirectory()) {
				File[] agentJARs = agentDir.listFiles(new FilenameFilter() {

					@Override
					public boolean accept(File dir, String name) {
						File file = new File(dir, name);
						return file.isFile() && file.getName().endsWith(".jar");
					}

				});
				agents = new IAgent[agentJARs.length];
				for (int i = 0; i < agentJARs.length; i++) {
					URLClassLoader agentLoader = new URLClassLoader(new URL[] { agentJARs[i].toURL() },
							URLClassLoader.getSystemClassLoader());
					JarFile agentJAR = new JarFile(agentJARs[i]);
					Enumeration<JarEntry> entries = agentJAR.entries();
					while (entries.hasMoreElements()) {
						JarEntry entry = entries.nextElement();
						if (entry.getName().endsWith(".class")) {
							try {
								Class<? extends IAgent> agentTest = (Class<? extends IAgent>) agentLoader
										.loadClass(entry.getName().replace('/', '.').substring(0,
												entry.getName().length() - 6));
								agents[i] = (IAgent) agentTest.newInstance();
								System.out.println("已成功加载" + agentJARs[i].getName() + "的" + entry.getName() + "。");
								break;
							} catch (Error e) {
								System.out.println("将跳过" + agentJARs[i].getName() + "的" + entry.getName() + "。");
							} catch (Exception e) {
								System.out.println("将跳过" + agentJARs[i].getName() + "的" + entry.getName() + "。");
							}
						}
					}
				}
			}
			GameController game = new GameController(10, 10, 60, 3);
			if (agents != null && agents.length > 0)
				for (IAgent agent : agents) {
					if (agent == null)
						continue;
					game.registerAgent(agent);
				}
			game.selectAgent(-1);
			game.startGame();
			game = null;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
